package cn.edu.scnu.semart.goods.service.Impl;

import cn.edu.scnu.semart.goods.service.GoodsService;
import cn.edu.scnu.semart.model.goods.Comment;
import cn.edu.scnu.semart.goods.mapper.CommentMapper;
import cn.edu.scnu.semart.goods.service.CommentService;
import cn.edu.scnu.semart.model.goods.Goods;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商品评论Service实现类
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Override
    public boolean addComment(Comment comment) {
        // 设置默认值
        if (comment.getStatus() == null) {
            comment.setStatus(1); // 默认通过审核
        }
        if (comment.getLikes() == null) {
            comment.setLikes(0);
        }
        
        return save(comment);
    }

    @Override
    public IPage<Comment> getCommentsByGoodsId(Integer goodsId, Page<Comment> page) {
        return baseMapper.selectCommentsByGoodsId(page, goodsId);
    }

    @Override
    public IPage<Comment> getCommentsByUserId(Integer userId, Page<Comment> page) {
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .eq("status", 1)
                .eq("deleted", 0)
                .orderByDesc("create_time");
        return page(page, queryWrapper);
    }

    @Override
    public boolean deleteComment(Integer id, Integer userId) {
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id).eq("user_id", userId);
        return remove(queryWrapper);
    }

    @Override
    public boolean likeComment(Integer commentId, Integer userId) {
        UpdateWrapper<Comment> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", commentId)
                    .setSql("likes = likes + 1");
        return update(updateWrapper);
    }

    @Override
    public boolean unlikeComment(Integer commentId, Integer userId) {
        UpdateWrapper<Comment> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", commentId)
                    .setSql("likes = likes - 1");
        return update(updateWrapper);
    }

    @Autowired
    private GoodsService goodsService;

    @Override
    public IPage<Comment> getReceivedComments(Integer userId, Page<Comment> page) {
        // 1. 查询该用户发布的商品ID列表
        QueryWrapper<Goods> goodsQuery = new QueryWrapper<>();
        goodsQuery.select("id").eq("user_id", userId).eq("deleted", 0);
        List<Goods> goodsList = goodsService.list(goodsQuery);

        if (goodsList.isEmpty()) {
            return new Page<>(page.getCurrent(), page.getSize(), 0);
        }

        List<Integer> goodsIds = goodsList.stream()
                .map(Goods::getId)
                .collect(Collectors.toList());

        // 2. 查询这些商品的评论
        QueryWrapper<Comment> commentQuery = new QueryWrapper<>();
        commentQuery.in("goods_id", goodsIds)
                .eq("status", 1)
                .eq("deleted", 0)
                .orderByDesc("create_time");

        return page(page, commentQuery);
    }

    @Override
    public Double getUserAverageRating(Integer userId) {
        // 1. 查询该用户发布的商品ID列表
        QueryWrapper<Goods> goodsQuery = new QueryWrapper<>();
        goodsQuery.select("id").eq("user_id", userId).eq("deleted", 0);
        List<Goods> goodsList = goodsService.list(goodsQuery);

        if (goodsList.isEmpty()) {
            return 0.0; // 如果没有商品，返回0分
        }

        List<Integer> goodsIds = goodsList.stream()
                .map(Goods::getId)
                .collect(Collectors.toList());

        // 2. 计算这些商品评论的平均分
        QueryWrapper<Comment> commentQuery = new QueryWrapper<>();
        commentQuery.select("AVG(rating) as avgRating")
                .in("goods_id", goodsIds)
                .eq("status", 1)
                .eq("deleted", 0);

        Map<String, Object> map = getMap(commentQuery);
        if (map == null || map.get("avgRating") == null) {
            return 0.0;
        }

        return ((Number)map.get("avgRating")).doubleValue();
    }


    @Override
    public CommentStatistics getCommentStatistics(Integer goodsId) {
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goods_id", goodsId).eq("status", 1);
        
        CommentStatistics statistics = new CommentStatistics();
        
        // 获取总评论数
        Integer totalCount = Math.toIntExact(count(queryWrapper));
        statistics.setTotalCount((int) totalCount);
        
        // 获取各星级评论数
        for (int i = 1; i <= 5; i++) {
            QueryWrapper<Comment> starQuery = new QueryWrapper<>();
            starQuery.eq("goods_id", goodsId)
                    .eq("status", 1)
                    .eq("rating", i);
            Integer starCount = Math.toIntExact(count(starQuery));
            
            switch (i) {
                case 1:
                    statistics.setOneStarCount((int) starCount);
                    break;
                case 2:
                    statistics.setTwoStarCount((int) starCount);
                    break;
                case 3:
                    statistics.setThreeStarCount((int) starCount);
                    break;
                case 4:
                    statistics.setFourStarCount((int) starCount);
                    break;
                case 5:
                    statistics.setFiveStarCount((int) starCount);
                    break;
            }
        }
        
        // 计算平均评分
        if (totalCount > 0) {
            QueryWrapper<Comment> avgQuery = new QueryWrapper<>();
            avgQuery.eq("goods_id", goodsId)
                    .eq("status", 1)
                    .select("AVG(rating) as avg_rating");
            // 这里需要自定义查询来获取平均分，简化处理
            double avgRating = (statistics.getFiveStarCount() * 5 + 
                              statistics.getFourStarCount() * 4 + 
                              statistics.getThreeStarCount() * 3 + 
                              statistics.getTwoStarCount() * 2 + 
                              statistics.getOneStarCount()) / (double) totalCount;
            statistics.setAverageRating(avgRating);
        }
        
        return statistics;
    }
} 